<template>
  <div>
    <div>商品清单如下：</div>
    <br />
    <div v-for="(item, index) in food" :key="index">
      {{ item.shopName }} {{ item.price }}元/份
    </div>
    <br />
    <div>请选择购买数量：</div>
    <br />
    <snacks
      v-for="(item, index) in food"
      :key="-index - 1"
      :food="item"
      :index="index"
      @changeAction="changeFn"
    ></snacks>
    <br />
    <div>总价为：{{ total }}</div>
  </div>
</template>

<script>
import snacks from "./components/snacks";
export default {
  components: {
    snacks,
  },
  computed: {
    total() {
      return this.food.reduce((sum, current) => {
        return sum + current.count * current.price;
      }, 0);
    },
  },
  methods: {
    changeFn(type, index) {
      if (type === "add") this.food[index].count++;
      else if (type === "del")
        this.food[index].count > 0 ? this.food[index].count-- : 0;
    },
  },
  data() {
    return {
      food: [
        {
          shopName: "可比克薯片",
          price: 5.5,
          count: 0,
        },
        {
          shopName: "草莓酱",
          price: 3.5,
          count: 0,
        },
        {
          shopName: "红烧肉",
          price: 55,
          count: 0,
        },
        {
          shopName: "方便面",
          price: 12,
          count: 0,
        },
      ],
    };
  },
};
</script>
<style>
</style>